﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;

namespace mns
{

    class UIMM
    {
        
        public enum UIMM_MSG { NULL, NOTIFY, RESPONSE };
        public UIMM_MSG cmd{set;get;}
        public object data { set; get; }

    }


    class MSG
    {
        AutoResetEvent msgevent;
        Queue msgqueue;

        public MSG()
        {
            msgqueue = new Queue();
            
            msgevent = new AutoResetEvent(false);
            msgevent.Reset();
        }

        public bool SendMessage(object val)
        {
            msgqueue.Enqueue(val);
            msgevent.Set();
            return true;
        }

        public bool GetMessage(out object val,int intervals = 1)
        {
            
            if(!msgevent.WaitOne(intervals))
            {
                val = null;
                return false;
            }
            val = msgqueue.Dequeue();
            if (msgqueue.Count.Equals(0))
            {
                msgevent.Reset();
            }
            else
            {
                msgevent.Set();
            }
            return true;
        }

        public bool IsThereMessage()
        {
            return !msgqueue.Count.Equals(0);
        }
    }

    static class MSGL
    {
        static Hashtable msgchannels = new Hashtable();
        static int id = 0;

        
        public static int CreateMsg()
        {
            id++;
            MSG msgqueue = new MSG();
            msgchannels.Add(id, msgqueue);
            return id;
        }
        
        public static bool SendMessage(int id,object val)
        {
            if(!msgchannels.ContainsKey(id))
            {
                return false;
            }

            return ((MSG)msgchannels[id]).SendMessage(val);
             
        }

        public static bool GetMessage(int id,out object val,int intervals = 1)
        {
            val = null;
            if (!msgchannels.ContainsKey(id))
            {
                return false;
            }
            return ((MSG)msgchannels[id]).GetMessage(out val,intervals);     
        }

    }

}
